﻿using System.Globalization;
using System.IO;
using NGettext;

namespace Fuse8.ContentManagementFramework.SystemFacade.Globalization.NGetText
{
    public class NGetTextFacade : GetTextFacadeBase
    {
        protected override IGetTextProvider GetForDomain(string name, CultureInfo locale)
        {
            var folder = GlobalizationFacade.MoFilesFinder.GetPath(name);
            string file;
            var fileExists = TryGetFilename(name, folder, locale.Name, out file) ||
                             TryGetFilename(name, folder, locale.TwoLetterISOLanguageName, out file);
            if (fileExists)
            {
                using (var stream = File.OpenRead(file))
                {
                    return new NGetTextProvider(new Catalog(stream, locale));
                }                
            }
            return new NGetTextProvider(new Catalog(name, folder, locale));
        }

        private bool TryGetFilename(string name, string folder, string locale, out string file)
        {
            file = Path.Combine(folder, locale, name) + ".mo";
            return File.Exists(file);
        }
    }
}